/**
 * Created by HMH on 2017/7/9.
 */
import axios from 'axios'
import router from '../router'
import * as $utils from './HHUtil'
import Cookies from 'js-cookie';
import $store from '../store/index';

let service = axios.create({
  timeout: 100000
});

service.defaults.headers.common['Content-Type'] = "multipart/form-data";

/**
 * response interceptors
 */
service.interceptors.response.use(
  response => {
    // console.log("==> response.data.errcode: ", response.data.errcode);
    if (response.data.errcode === 0) {
      
      // console.log(" ⛅ get response with data", response.data);
      return Promise.resolve(response.data.data);
      
    }
    if (response.data.errcode === 101) {
      
      console.log("==> 错误码为101");
      router.push({
        path: '/user/register'
      });
      
    } else {
      return Promise.reject(response.data);
    }
  },
  error => {
    console.log(' 🌧 get native http error', error.response);
    // 如果错误存在响应则处理
    if (error.response) {
      console.log(error.response.status);
      switch (error.response.status) {
        case 405:
          error.message = '系统请求了错误的Http方法';
          break;
        case 401:
          router.push({
            path: '/login'
          });
          break;
        case 412:
          router.push({
            path: '/login'
          });
      }
      
      // 获取参数
      let message = error.message;
      let response = error.response;
      let data = response.data;
      
      console.log(" 🌧 response err occur", message)
      
      // 如果响应存在数据，则是后台已经处理的错误
      if ($utils.hasValue(data.errcode)) {
        var errmsg = data.errmsg;
        console.log(' 🌧 err occur ', errmsg);
        return Promise.reject(data);
      } else {
        //自动生成的error
        const err = {
          'errcode': response.status,
          'errmsg': message
        };
        return Promise.reject(err);
      }
    }
  }
);

/**
 * 请求拦截器
 */
service.interceptors.request.use(
  config => {
  
    const token = $store.getters.token;
    
    // console.log(" ⛅ add header");
    config.headers.common['week-authentication'] = token;
    config.headers.common['Content-Type'] = "multipart/form-data";
    // config.headers.common['Content-Type'] = "application/json";
    return config;
  },
  err => {
    console.log(" 🌧 request error occur",err);
    return Promise.reject(err);
  }
);




//暴露接口
export default service;
